
"""
Register a connector function for obtaining a connection to a gadfly SQL database
before executing the dispatcher.

(primarily for testing).
"""

import chatLogic
from whiff.middleware import misc
from whiff import resolver
from whiff import whiffenv

class MySqlConnection(misc.utility):
    def __init__(self,
                 Dispatcher,
                 CredentialsPath,
                 DbPrefix="gfChat",
                 AutoCreateTables=False,
                 ):
        self.Dispatcher = Dispatcher
        self.AutoCreateTables = AutoCreateTables
        self.CredentialsPath = CredentialsPath
        self.DbPrefix = DbPrefix
    def __call__(self, env, start_response):
        # materialize parameters
        CredentialsPath = self.param_value(self.CredentialsPath, env).strip()
        AutoCreateTables = self.param_json(self.AutoCreateTables, env)
        DbPrefix = self.param_value(self.DbPrefix, env).strip()
        # define the connector function
        def getConnection():
            connection = chatLogic.mySqlConnection(CredentialsPath, DbPrefix)
            # note: this will not create the database: just the tables if they are not there and the database exists.
            if AutoCreateTables:
                connection.autoCreateTables()
            return connection
        env = chatLogic.registerConnector(getConnection, env)
        # deliver the dispatch page
        return self.deliver_page(self.Dispatcher, env, start_response)

__middleware__ = MySqlConnection

